﻿using System;
using System.Collections.Generic;

using aier.dataaccess.model;
using aier.dataaccess.dapper;
using aier.xrm.wcf;

using Microsoft.Xrm.Sdk;
using log4net;
using System.Linq;
using Microsoft.Xrm.Sdk.Messages;
using System.ServiceModel;

namespace aier.business.logic
{
    public partial class CommonBll
    {
        public ILog log { get; set; }
        public AppointmentBll appointmentBll { get; set; }
        public LeadBll leadBll { get; set; }
        public StreetBll streetBll { get; set; }
        public ResResult resResult { get; set; }
        public CommonWcf commonWcf { get; set; }
        public SchoolBll schoolBll { get; set; }
        public ScreenBll screenBll { get; set; }
        public ContactBll contactBll { get; set; }
        public HospitalBll hospitalBll { get; set; }
        public SequenceBll sequenceBll { get; set; }
        public ReservationBll reservationBll { get; set; }
        public ScreenResultBll screenResultBll { get; set; }
        public ScreenCustomerBll screenCustomerBll { get; set; }
        public ScreenEquipmentBll screenEquipmentBll { get; set; }
        public ScreenPropagandaBll screenPropagandaBll { get; set; }

        public EquipmentDal equipmentDal { get; set; }

        public ProvinceBll provinceBll { get; set; }
        public CityBll cityBll { get; set; }
        public AreaBll areaBll { get; set; }

        public DoctorBll doctorBll { get; set; }

        public CompetitorBll competitorBll { get; set; }

        /// <summary>
        /// 更新任务实体的系统状态
        /// </summary>
        /// <param name="entityId">实体ID</param>
        /// <param name="statecode">实体状态</param>
        /// <param name="entitylocalName">实体名字</param>
        public void UpdateEntityState(Guid entityId, int statecode, string entitylocalName)
        {
            commonWcf.UpdateStateRequest(entityId, statecode, entitylocalName);
        }




        /// <summary>
        /// 保存学校及联系人信息,
        /// 根据学校ID，联系人ID来判断 是新增/修改学校，联系人实体
        /// 新增时实体ID为空，修改时实体ID为必填
        /// 原程序 :ScSchoolServiceImpl-> saveSchool(AierSchoolInfo school)
        /// </summary>
        /// <param name="school">学校</param>
        /// <param name="contact">联系人</param>
        /// <returns></returns>
        public ResResult SaveSchool(School school)
        {
            try
            {
                //获取省市区
                var pcaid = streetBll.GetPCAByName(school?.provinceName, school?.cityName, school?.areaName);
                if (pcaid != null)
                {
                    school.new_province = pcaid.Item1;
                    school.new_city = pcaid.Item2;
                    school.new_area = pcaid.Item3;
                }

                ContactInfo contact = new ContactInfo();

                contact.Lastname = school.new_contactName;
                contact.userid = school.userid;
                contact.New_type = 1;
                contact.MobilePhone = school.new_mobile;
                //1、判断联系人是否存在,不存在则创建，否则更新
                if (Guid.Empty.Equals(school.new_contact) || null == school.new_contact)
                {
                    resResult = contactBll.AddContact(contact);
                }
                else
                {
                    contact.Contactid = school.new_contact.Value;
                    resResult = contactBll.ModContact(contact);
                }

                //2、为学校联系人ID赋值
                if (resResult.ResultState == 1) school.new_contact = resResult.Result;

                //3、根据学校ID判断新增/修改学校信息
                if (Guid.Empty.Equals(school.new_schoolId))
                {
                    resResult = schoolBll.CreateSchool(school);
                }
                else
                {
                    resResult = schoolBll.UpdateSchoolById(school);
                }

                return resResult.SuccessResult("CommonBll-> SaveSchool :" + resResult.Result);
            }
            catch (Exception ex)
            {
                log.Error("CommonBll-> SaveSchool :" + ex.Message);
                return resResult.FailResult("CommonBll-> SaveSchool :" + ex.Message);
            }
        }





        /// <summary>
        /// 创建 推荐记录、潜在客户、预约记录
        /// recommendInfo不用传leadid，leadInfo传入姓名和手机号码就可以
        /// 原程序 RecommendServiceImpl/addRecommend
        /// </summary>
        /// <param name="recommendModel">推荐记录</param>
        /// <param name="leadInfo">潜在客户</param>
        /// <returns>返回推荐记录ID</returns>
        public ResResult AddRecommendAndLead(RecommendView recommend, UserInfo userInfo)
        {
            Guid userid = userInfo.userid;
            RecommendModel recommendModel = GetRecommendModel(recommend, userid);
            LeadInfo leadInfo = GetLeadModel(recommend, userid);
            leadInfo.new_patientsource = 4;

            //学术推广的渠道来源，如果配置了村医，那么 渠道应该为学术推广
            //2020/2/13 Louis

            string userRole = userInfo.mobilerole_systemuser;
            string[] userRoles = userRole.Split('|');
            if (userRoles.Contains("13"))
            {
                leadInfo.new_patientsource = 3;
            }


            ResResult resResult = new ResResult();
            Guid leadid = QueryLeadidOrCreate(leadInfo, recommendModel.userid);
            if (leadid == Guid.Empty)
            {
                resResult = resResult.FailResult("创建潜在客户失败");
                return resResult;
            }
            Guid recommendid = CreateRecommend(recommendModel, leadid,leadInfo.lastname);
            if (recommendid == Guid.Empty)
            {
                resResult = resResult.FailResult("创建推广记录失败");
                return resResult;
            }
            Guid reservationid = CreateReservation(recommendModel, leadInfo, leadid, recommendid);
            if (reservationid == Guid.Empty)
            {
                resResult = resResult.FailResult("创建预约记录");
                return resResult;
            }
            resResult = resResult.SuccessResult(recommendid);
            return resResult;
        }

        /// <summary>
        /// 修改 推荐记录、潜在客户、预约记录
        /// recommendInfo不用传leadid，leadInfo传入姓名和手机号码就可以
        /// recommendModel、leadInfo 实体ID为必填
        /// 原程序 RecommendServiceImpl/modRecommend
        /// </summary>
        /// <param name="recommendModel">推荐记录</param>
        /// <param name="leadInfo">潜在客户</param>
        /// <param name="isModReservation">isModReservation=1则修改最后一次预约对象</param>
        public ResResult UpdateRecommendAndLead(RecommendView recommend, UserInfo userInfo, string isModReservation)
        {
            Guid userid = userInfo.userid;
            RecommendModel recommendModel = GetRecommendModel(recommend, userid);
            LeadInfo leadInfo = GetLeadModel(recommend, userid);
            leadInfo.new_patientsource = 4;

            string userRole = userInfo.mobilerole_systemuser;
            string[] userRoles = userRole.Split('|');
            if (userRoles.Contains("13"))
            {
                leadInfo.new_patientsource = 3;
            }

            ResResult leadResult = UpdateLead(leadInfo);
            if (resResult.ResultState == 0)
            {
                return leadResult;
            }
            bool isoperate = false;
            Guid reservationid = Guid.Empty;
            QueryReservationInfo(leadInfo, out isoperate, out reservationid);
            if (isModReservation == "1")
            {
                ResResult reservationResult = ReservationCreateOrUpdate(recommendModel, leadInfo, reservationid);
                if (reservationResult.ResultState == 0)
                {
                    return reservationResult;
                }
            }
            ResResult RecommendResult = UpdateRecommend(recommendModel, isoperate);
            return RecommendResult;
        }

        private LeadInfo GetLeadModel(RecommendView recommend, Guid userid)
        {
            LeadInfo leadInfo = new LeadInfo();
            if (recommend.new_lead != null)
            {
                leadInfo.leadid = Guid.Parse(recommend.new_lead.ToString());
            }
            if (!string.IsNullOrWhiteSpace(recommend.Address1_Telephone1))
            {
                leadInfo.address1_telephone1 = recommend.Address1_Telephone1;
                leadInfo.new_phone = recommend.Address1_Telephone1;
            }
            if (!string.IsNullOrWhiteSpace(recommend.new_leadName))
            {
                leadInfo.lastname = recommend.new_leadName;
            }
            if (recommend.new_gender != null)
            {
                leadInfo.new_gender = recommend.new_gender;
            }
            if (recommend.new_age != null)
            {
                leadInfo.new_age = recommend.new_age;
            }
            if (!string.IsNullOrWhiteSpace(recommend.new_citizenid))
            {
                leadInfo.new_citizenid = recommend.new_citizenid;
            }
            if (!string.IsNullOrWhiteSpace(recommend.telephone2))
            {
                leadInfo.telephone2 = recommend.telephone2;
            }
            if (recommend.new_birthdate != null)
            {
                leadInfo.new_birthdate = recommend.new_birthdate;
            }
            //新增学术推广（村医、外部转诊、e站接口数据，不含内部转诊）记录时需对应潜客写入机构信息、合作医生信息
            //2020/2/12 Louis
            if (recommend.new_contact != null)
            {
                leadInfo.new_coopdoctorid = recommend.new_contact;
            }
            if (recommend.new_networkhospitalwherethehospital != null)
            {
                leadInfo.new_medicalinstitutionid = recommend.new_networkhospitalwherethehospital;
            }


            leadInfo.userid = userid;
            return leadInfo;
        }

        private RecommendModel GetRecommendModel(RecommendView recommend, Guid userid)
        {
            RecommendModel recommendModel = new RecommendModel();
            if (recommend.new_recommendId != null)
            {
                recommendModel.new_recommendId = recommend.new_recommendId;
            }
            if (recommend.new_content != 0)
            {
                recommendModel.new_content = recommend.new_content;
            }
            if (!string.IsNullOrWhiteSpace(recommend.new_remark))
            {
                recommendModel.new_remark = recommend.new_remark;
            }
            if (recommend.new_hospital != null)
            {
                recommendModel.new_hospital = recommend.new_hospital;
            }
            if (recommend.new_appointmenttothehospitaldate != null)
            {
                recommendModel.new_appointmenttothehospitaldate = recommend.new_appointmenttothehospitaldate;
            }
            if (recommend.new_contact != null)
            {
                recommendModel.new_contact = recommend.new_contact;
            }
            if (recommend.new_networkhospitalwherethehospital != Guid.Empty)
            {
                recommendModel.new_networkhospitalwherethehospital = recommend.new_networkhospitalwherethehospital;
            }
            //DoctorBll doctor = new DoctorBll();
            if (recommend.new_contact != Guid.Empty)
            {
                ContactView contact = doctorBll.QryDoctorById((Guid)recommend.new_contact);
                if (contact != null)
                {
                    if (contact.new_type == 3)
                    {//村医
                        recommendModel.new_referraltype = 100000002;//村医转诊
                    }
                    else if (contact.new_type == 1)
                    {//外部
                        recommendModel.new_referraltype = 100000001;//外部转诊       
                    }
                    else if (contact.new_type == 2)
                    {//内部
                        recommendModel.new_referraltype = 100000000;//内部转诊  
                    }
                    if (!string.IsNullOrEmpty(contact.LastName)) {
                        recommendModel.new_name = contact.LastName;
                    }
                }
            }
            if ((recommend.new_networkhospitalwherethehospital != Guid.Empty) && recommend.new_networkhospitalwherethehospital != null)
            {
                CompetitorView competitorView = competitorBll.QueryCompetitor((Guid)recommend.new_networkhospitalwherethehospital);
                if (competitorView != null) {
                    if (competitorView.new_iscoopmedicalcouplet!=null) {
                        recommendModel.new_ismedicalcouplet = (bool)competitorView.new_iscoopmedicalcouplet;
                    }
                }  
            }
            recommendModel.userid = userid;
            return recommendModel;
        }

        /// <summary>
        /// 创建或更新预约记录
        /// </summary>
        /// <param name="recommendModel"></param>
        /// <param name="leadInfo"></param>
        /// <param name="reservationid"></param>
        /// <returns></returns>
        private ResResult ReservationCreateOrUpdate(RecommendModel recommendModel, LeadInfo leadInfo, Guid reservationid)
        {
            ResResult reservationResult = null;
            if (reservationid == Guid.Empty)
            {
                reservationid = CreateReservation(recommendModel, leadInfo, leadInfo.leadid, recommendModel.new_recommendId);
                if (reservationid == Guid.Empty)
                {
                    reservationResult = resResult.FailResult("创建预约记录失败");
                }
                else
                {
                    reservationResult = resResult.SuccessResult();
                }
            }
            else
            {
                reservationResult = UpdateReservation(recommendModel, leadInfo, leadInfo.leadid, recommendModel.new_recommendId, reservationid);
            }

            return reservationResult;
        }

        /// <summary>
        /// 更新推荐记录
        /// </summary>
        /// <param name="recommendModel">推荐记录</param>
        /// <param name="isoperate">到院确认</param>
        /// <returns></returns>
        private ResResult UpdateRecommend(RecommendModel recommendModel, bool isoperate)
        {
            try
            {
                if (recommendModel.new_recommendId == Guid.Empty)
                {
                    return resResult.FailResult("recommendModel.new_recommendId不能为空");
                }
                if (isoperate)
                {
                    recommendModel.new_istohospital = true;
                }
                Entity recommendEntity = recommendModel.AsCrmEntity();
                if (recommendModel.userid == Guid.Empty)
                {
                    commonWcf.UpdateEntityById(recommendEntity);
                }
                else
                {
                    commonWcf.UpdateEntityProxyById(recommendModel.userid, recommendEntity);
                }
                return resResult.SuccessResult();
            }
            catch (Exception ex)
            {
                log.Error("CommonBll对象中，UpdateRecommend方法:" + ex.StackTrace + ex.Message);
                return resResult.FailResult(ex.Message);
            }

        }

        /// <summary>
        /// 查询预约信息返回第一条数据 orderby createon desc
        /// </summary>
        /// <param name="leadInfo">意向客户</param>
        /// <param name="isoperate">到院确认</param>
        /// <param name="recommendid">推荐记录ID</param>
        private void QueryReservationInfo(LeadInfo leadInfo, out bool isoperate, out Guid new_reservationId)
        {
            var reservationView = reservationBll.QueryReservationByLeadId(leadInfo.leadid);
            if (reservationView != null)
            {
                isoperate = Convert.ToBoolean(reservationView.new_isoperate);
                new_reservationId = Guid.Parse(reservationView.new_reservationId.ToString());
            }
            else
            {
                isoperate = false;
                new_reservationId = Guid.Empty;
            }
        }

        /// <summary>
        /// 更新意向客户
        /// </summary>
        /// <param name="leadInfo"></param>
        /// <returns></returns>
        private ResResult UpdateLead(LeadInfo leadInfo)
        {
            try
            {
                if (leadInfo.leadid == Guid.Empty)
                {
                    resResult = resResult.FailResult("潜在客户ID不能为空");
                    return resResult;
                }
                //if (string.IsNullOrWhiteSpace(leadInfo.lastname))
                //{
                //    resResult = resResult.FailResult("客户姓名不能为空");
                //    return resResult;
                //}
                Entity leadEntity = leadInfo.AsCrmEntity();
                if (leadInfo.userid == Guid.Empty)
                {
                    commonWcf.UpdateEntityById(leadEntity);
                }
                else
                {
                    commonWcf.UpdateEntityProxyById(leadInfo.userid, leadEntity);
                }
                return resResult.SuccessResult();
            }
            catch (Exception ex)
            {
                log.Error("CommonBll对象中，UpdateLead方法:" + ex.StackTrace + ex.Message);
                return resResult.FailResult(ex.Message);
            }

        }

        /// <summary>
        /// 创建预约记录
        /// </summary>
        /// <param name="recommendModel">推广记录</param>
        /// <param name="leadInfo">潜在客户</param>
        /// <param name="ownerid">负责人</param>
        /// <param name="leadid">潜在客户ID</param>
        /// <param name="recommendid">推广记录ID</param>
        /// <returns></returns>
        private Guid CreateReservation(RecommendModel recommendModel, LeadInfo leadInfo, Guid leadid, Guid recommendid)
        {
            Guid reservationid = Guid.Empty;
            try
            {
                Entity reservationEntity = GetReservationEntity(recommendModel, leadInfo, leadid, recommendid);
                if (recommendModel.userid == Guid.Empty)
                {
                    reservationid = commonWcf.CreateEntity(reservationEntity);
                }
                else
                {
                    reservationid = commonWcf.CreateEntityProxy(recommendModel.userid, reservationEntity);
                }
            }
            catch (Exception ex)
            {
                recommendid = Guid.Empty;
                log.Error("CommonBll对象中，CreateReservation方法:" + ex.StackTrace + ex.Message);
            }

            return reservationid;
        }
        /// <summary>
        /// 更新预约记录
        /// </summary>
        /// <param name="recommendModel">推广记录</param>
        /// <param name="leadInfo">潜在客户</param>
        /// <param name="ownerid">负责人</param>
        /// <param name="leadid">潜在客户ID</param>
        /// <param name="recommendid">推广记录ID</param>
        /// <param name="reservationid">预约记录ID</param>
        /// <returns></returns>
        private ResResult UpdateReservation(RecommendModel recommendModel, LeadInfo leadInfo, Guid leadid, Guid recommendid, Guid reservationid)
        {
            try
            {
                Entity reservationEntity = GetReservationEntity(recommendModel, leadInfo, leadid, recommendid, reservationid);
                if (recommendModel.userid == Guid.Empty)
                {
                    commonWcf.UpdateEntityById(reservationEntity);
                }
                else
                {
                    commonWcf.UpdateEntityProxyById(recommendModel.userid, reservationEntity);
                }
                return resResult.SuccessResult();
            }
            catch (Exception ex)
            {

                log.Error("CommonBll对象中，UpdateReservation方法:" + ex.StackTrace + ex.Message);
                return resResult.FailResult(ex.Message);
            }

        }

        private static Entity GetReservationEntity(RecommendModel recommendModel, LeadInfo leadInfo, Guid leadid, Guid recommendid, Guid? reservationid = null)
        {
            Reservation reservation = new Reservation();
            reservation.new_lead = leadid;
            reservation.new_source = leadInfo.new_patientsource;
            if (reservationid != null)
            {
                reservation.new_reservationid = Guid.Parse(reservationid.ToString());
            }
            if (leadInfo.new_age != null)
            {
                reservation.new_age = leadInfo.new_age;
            }
            if (leadInfo.new_gender != null)
            {
                reservation.new_gender = leadInfo.new_gender;
            }
            if (!string.IsNullOrWhiteSpace(leadInfo.new_insuranceid))
            {
                reservation.new_insuranceid = leadInfo.new_insuranceid;
            }
            if (leadInfo.new_insurancetype != null)
            {
                reservation.new_insurancetype = leadInfo.new_insurancetype;
            }
            if (!string.IsNullOrWhiteSpace(leadInfo.address1_telephone1))
            {
                reservation.new_mobile = leadInfo.address1_telephone1;
            }
            if (!string.IsNullOrWhiteSpace(leadInfo.new_qq))
            {
                reservation.new_qq = leadInfo.new_qq;
            }
            if (!string.IsNullOrWhiteSpace(leadInfo.new_wechat))
            {
                reservation.new_wechat = leadInfo.new_wechat;
            }
            if (recommendModel.new_appointmenttothehospitaldate != null)
            {
                reservation.new_reservationdate = recommendModel.new_appointmenttothehospitaldate;
            }
            if (recommendModel.new_hospital != Guid.Empty)
            {
                reservation.new_hospital = recommendModel.new_hospital;
            }
            reservation.new_recommend = recommendid;
            if (recommendModel.new_department != Guid.Empty)
            {
                reservation.new_department = recommendModel.new_department;
            }
            reservation.new_contnt = GetItemIndexByContent((int)recommendModel.new_content);
            
            Entity reservationEntity = reservation.AsCrmEntity();
            return reservationEntity;
        }

        /// <summary>
        /// 创建推广记录
        /// </summary>
        /// <param name="recommendModel">推荐记录</param>
        /// <param name="leadid">潜在客户ID</param>
        /// <returns></returns>
        private Guid CreateRecommend(RecommendModel recommendModel, Guid leadid,string leadName)
        {
            Guid recommendid = Guid.Empty;
            try
            {
                Entity recommendEentity = recommendModel.AsCrmEntity();
                recommendEentity["new_lead"] = new EntityReference("lead", leadid);
                string doctor = string.Empty;
                if (recommendEentity.Contains("new_name")) {
                    doctor = recommendEentity["new_name"].ToString();
                }
                recommendEentity["new_name"] = doctor  + "推荐的客户" + leadName;
                if (recommendModel.userid == Guid.Empty)
                {
                    recommendid = commonWcf.CreateEntity(recommendEentity);
                }
                else
                {
                    recommendid = commonWcf.CreateEntityProxy(recommendModel.userid, recommendEentity);
                }
            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                log.Error("CommonBll对象中，CreateRecommend方法:" + ex.Detail.ErrorCode + ex.Detail.Message, ex);

            }
            catch (Exception ex)
            {
                recommendid = Guid.Empty;
                log.Error("CommonBll对象中，CreateRecommend方法:" + ex.StackTrace + ex.Message, ex);
            }
            return recommendid;
        }

        /// <summary>
        /// 查找是否存在意向客户，不存在则创建
        /// </summary>
        /// <param name="leadInfo">潜在客户</param>
        /// <param name="ownerid">负责人ID</param>
        /// <returns></returns>
        private Guid QueryLeadidOrCreate(LeadInfo leadInfo, Guid ownerid)
        {
            Guid leadid = Guid.Empty;
            try
            {
                leadid = leadBll.QueryLeadidByConditions(leadInfo.lastname, ownerid, leadInfo.new_citizenid, leadInfo.address1_telephone1, "");
                if (leadid == Guid.Empty)
                {
                    //没有查出lead则创建新的lead
                    Entity leadEntity = leadInfo.AsCrmEntity();
                    //leadEntity["new_patientsource"] = new OptionSetValue(4);//来源方式 4 网医 
                    leadEntity["new_datasource"] = new OptionSetValue(17);//5:网医新增患者接口                    
                    if (ownerid == Guid.Empty)
                    {
                        leadEntity["ownerid"] = new EntityReference("systemuser", ownerid);
                        leadid = commonWcf.CreateEntity(leadEntity);
                    }
                    else
                    {
                        leadid = commonWcf.CreateEntityProxy(ownerid, leadEntity);
                    }
                }
            }
            catch (Exception ex)
            {
                leadid = Guid.Empty;
                log.Error("CommonBll对象中，QueryLeadidOrCreate方法:" + ex.StackTrace + ex.Message);
            }

            return leadid;
        }

        /// <summary>
        /// 拜访签到或完成
        /// </summary>
        public ResResult AppointmentCheckInOrCompelete(AppointmenMolde appointmenMolde, int stateCode, int statusCode)
        {
            try
            {
                if (appointmenMolde == null)
                {
                    return resResult.FailResult("CommonBll->AppointmentCheckIn Error: 签到失败 ,传入对象为空");
                }
                if (string.IsNullOrWhiteSpace(appointmenMolde.new_signinplace) || appointmenMolde.new_signintime == null)
                {
                    return resResult.FailResult("CommonBll->AppointmentCheckIn Error: 签到失败 ,签到时间或地点为空");
                }
                //进行签到地点等更新
                ResResult updateRes = appointmentBll.ModAppointment(appointmenMolde);
                if (updateRes.ResultState == 0)
                {
                    return resResult.FailResult("CommonBll->AppointmentCheckIn Error: 签到失败 " + updateRes.ResultMes);
                }
                //获取activityid
                Guid activityid = updateRes.Result;
                //更新系统状态
                ResResult updateStateRes = appointmentBll.UpdateStatus(activityid, stateCode, statusCode);
                if (updateRes.ResultState == 0)
                {
                    return resResult.FailResult("CommonBll->AppointmentCheckIn Error: 签到失败 " + updateStateRes.ResultMes);
                }
                return resResult.SuccessResult(activityid);
            }
            catch (Exception e)
            {
                log.Error("AppointmentCheckIn：" + e.Message);
                return resResult.FailResult("CommonBll->AppointmentCheckIn Error:" + e.Message);
            }
        }


        /// <summary>
        /// 创建医疗机构
        /// </summary>
        /// <returns></returns>
        public ResResult SaveCompetitor(CompetitorView competitorView, Guid userid)
        {
            ResResult result = new ResResult();
            CompetitorInfo competitorInfo = GetCompetitor(competitorView);

            try
            {
                if (competitorInfo == null)
                {
                    log.Error("SaveCompetitor 出现错误：传入对象为空");
                    result.ResultMes = "error:传入对象为空";
                    result.ResultState = 0;
                    return result;
                }
                Entity entity = competitorInfo.AsCrmEntity();
                if (entity.Contains("new_iscoopmedicalcouplet")) {
                    if (entity.GetAttributeValue<bool>("new_iscoopmedicalcouplet")) {
                        entity["new_mode"] = new OptionSetValue(1);
                    }
                }
                result.Result = commonWcf.CreateEntityProxy(userid, entity);
                result.ResultMes = "success";
                result.ResultState = 1;
                return result;
            }
            catch (Exception e)
            {
                log.Error("SaveCompetitor 出现错误：" + e.Message);
                result.ResultMes = "error:" + e.Message;
                result.ResultState = 0;
                return result;
            }
        }
        /// <summary>
        /// 获取医疗机构
        /// </summary>
        /// <param name="competitorView"></param>
        /// <returns></returns>
        private CompetitorInfo GetCompetitor(CompetitorView competitorView)
        {
            CompetitorInfo competitorInfo = new CompetitorInfo();
            Guid provinceid = provinceBll.GetProvinceIdByName(competitorView.new_provincename);
            Guid cityid = cityBll.GetCityIdByName(competitorView.new_marketname);
            Guid countryId = areaBll.GetAreaIdByName(competitorView.new_districtcountyname);
            competitorInfo.Name = competitorView.name;
            if (provinceid != Guid.Empty)
            {
                competitorInfo.New_province = provinceid;
            }
            if (cityid != Guid.Empty)
            {
                competitorInfo.New_market = cityid;
            }
            if (countryId != Guid.Empty)
            {
                competitorInfo.New_districtandcounty = countryId;
            }

            competitorInfo.New_iscoopmedicalcouplet = competitorView.new_iscoopmedicalcouplet;
            competitorInfo.New_type = competitorView.new_type;
            competitorInfo.New_mode = competitorView.new_mode;

            return competitorInfo;
        }

        /// <summary>
        /// 预约的项目与需求内容的对应关系
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        private static int? GetItemIndexByContent(int content) {
            int itemIndex = 0;
            //0, 1000000000, 100000001, 100000013, 100000002, 100000003, 100000005, 100000007, 
            //100000008, 100000009, 100000010, 100000011, 100000006, 100000012, 100000004, 100000014
            switch (content) {
                case 0:
                    itemIndex = 0;
                    break;
                case 100000000:
                    itemIndex = 1;
                    break;
                case 100000001:
                    itemIndex = 2;
                    break;
                case 100000013:
                    itemIndex = 3;
                    break;
                case 100000002:
                    itemIndex = 4;
                    break;
                case 100000003:
                    itemIndex = 5;
                    break;
                case 100000005:
                    itemIndex = 6;
                    break;
                case 100000007:
                    itemIndex = 7;
                    break;
                case 100000008:
                    itemIndex = 8;
                    break;
                case 100000009:
                    itemIndex = 9;
                    break;
                case 100000010:
                    itemIndex = 10;
                    break;
                case 100000011:
                    itemIndex = 11;
                    break;
                case 100000006:
                    itemIndex = 12;
                    break;
                case 100000012:
                    itemIndex = 13;
                    break;
                case 100000004:
                    itemIndex = 14;
                    break;
                case 100000014:
                    itemIndex = 15;
                    break;

            }
            return itemIndex;
        }

    }
}
